package com.example.demo.service;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * 邮件服务类
 */

@Service
public class SpringMailService {

    private final JavaMailSenderImpl defaultMailSender;

    private final JavaMailSenderImpl specialMailSender;

    public SpringMailService(@Qualifier("defaultMailSender") JavaMailSenderImpl defaultMailSender, @Qualifier("specialMailSender") JavaMailSenderImpl specialMailSender) {
        this.defaultMailSender = defaultMailSender;
        this.specialMailSender = specialMailSender;
    }

    /**
     * 发送简单邮件
     *
     * @param to      接受者
     * @param subject 主题
     * @param content 内容
     */
    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //发起者
        mailMessage.setFrom(defaultMailSender.getUsername());
        // 接受者
        mailMessage.setTo(to);

        //如果发给多个人的：
        //mailMessage.setTo("1xx.com","2xx.com","3xx.com");    
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        try {
            defaultMailSender.send(mailMessage);
            System.out.println("发送简单邮件");
        } catch (Exception e) {
            System.out.println("发送简单邮件失败");
        }
    }

    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = specialMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(specialMailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            specialMailSender.send(message);
            System.out.println("html格式邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("html格式邮件发送失败");
        }
    }

}